
// 获取元素
const player = document.querySelector(".player");
const video = player.querySelector(".viewer");
const toggleBtn = player.querySelector(".toggle");
const skipButtons = player.querySelectorAll("[data-skip]"); // 属性选择器

const progress = player.querySelector('.progress');
const progressBar = player.querySelector('.progress__filled');

const ranges = player.querySelectorAll('.player__slider');



// 暂停or播放
function togglePlay() {
    const method = video.paused ? "play" : "pause";
    video[method]();
}
// 暂停or播放对应的icon
function updateIcon() {
    const icon = this.paused ? '►' : '❚ ❚';
    toggleBtn.textContent = icon;
}

// 快进和快退
function skip() {
    // console.log(typeof this.dataset.skip); // string类型
    video.currentTime += parseFloat(this.dataset.skip);
}

// 进度条
function handleProgress() {
    progressBar.style.flexBasis = `${(video.currentTime / video.duration) * 100}%`;
}

// 改变音量或播放速度
function updateRange() {
    video[this.name] = this.value;
}

function scrub(e) {
    // video.currentTime = (e.offsetX / this.offsetWidth) * video.duration; // 这里不能使用this，this为window对象
    video.currentTime = (e.offsetX / progress.offsetWidth) * video.duration;
}

// 绑定事件
// 播放暂停
toggleBtn.addEventListener("click", togglePlay);
video.addEventListener("click", togglePlay);
toggleBtn.addEventListener("click", updateIcon);
video.addEventListener("click", updateIcon);

// 快进快退
skipButtons.forEach(skipButton => skipButton.addEventListener("click", skip));
// 进度条展示
// timeupdate:currentTime 属性指定的时间发生变化（一直处于播放情况）
video.addEventListener("timeupdate", handleProgress);
// 点击进度框可修改进度条
progress.addEventListener("mousedown", scrub);
progress.addEventListener("click", scrub);

// 改变音量和播放速度
ranges.forEach(range => range.addEventListener("change", updateRange));

